define([
    "UtilDir/util",
    "UtilDir/tool",
    "UtilDir/org/selectOrg",
    "UtilDir/searchBlock",
    "static/app/fxpg/util/js/loading",
    "Date", "DateCN", "css!DateCss",
    "EasyUI", "EasyUI-lang"
], function (Util, Tool, SelectOrg, SearchBlock, Loading) {

    var sysPath = getServer() + "/static/app/fxpg/fxCasulatyEstimate";

    var fxCasulatyEstimateFormHtml = sysPath + "/views/fxCasulatyEstimateForm.html";
    var getFxCasulatyEstimateController = function () {
        return getServer() + "/fxCasulatyEstimates";
    };

    /**
     * 页面初始化
     */
    var init = function () {
        initSearchBlock();
        queryBtnBind();
        initProvinceSelect("北京市", "北京市", "东城区");
        initCasulatySelect();
        initPeriodSelect();

    };
    // 搜索栏省市区
    var initProvinceSelect = function (Province, City, Area) {
        debugger;
        var html = "";
        $("#citySelect").append(html);
        $("#areaSelect").append(html);
        $.ajax({
            url: getServer() +"/divisions/root/subdivisions",
            contentType: "application/json",
            type: "get",
            success: function (data) {
                $.each(data, function (idx, item) {
                    if (item.divisionName == Province) {
                        debugger;
                        var divisionId = item.divisionId;
                        var htmlCity = '';
                        if (Province == "北京市" || Province == "天津市" || Province == "上海市" || Province == "重庆市") {
                            $("#citySelect").append("<option value='" + Province + "' exid='" + divisionId + "'>" + Province + "</option>");
                            $('#citySelect').val(City);
                            var htmlArea = '';
                            $.ajax({
                                url: getServer() +"/divisions/" + divisionId + "/subdivisions",
                                contentType: "application/json",
                                type: "get",
                                success: function (data) {
                                    $.each(data, function (idx, item) {
                                        htmlArea += "<option value='" + item.divisionName + "' exid='" + item.divisionId + "'>" + item.divisionName + "</option>";
                                    });
                                    $("#areaSelect").append(htmlArea);
                                    $('#areaSelect').val(Area);
                                    // 列表
                                    createFxCasulatyEstimateGrid();
                                    // 计算按钮
                                    $("#btnCaculate").click(function () {
                                        if ($("#provinceSelect").val() == null) {
                                            Util.alert("请选择省");
                                            return;
                                        }
                                        if ($("#citySelect").val() == null) {
                                            Util.alert("请选择市");
                                            return;
                                        }
                                        if ($("#areaSelect").val() == null) {
                                            Util.alert("请选择区（县）");
                                            return;
                                        }
                                        calculate();
                                    });
                                }
                            });

                        } else {
                            $.ajax({
                                url: getServer() +"/divisions/" + divisionId + "/subdivisions",
                                contentType: "application/json",
                                type: "get",
                                success: function (data) {
                                    debugger;
                                    $.each(data, function (idx, item) {
                                        if (item.divisionName == City) {
                                            var divisionId = item.divisionId;
                                            var htmlArea = '';
                                            $.ajax({
                                                url: getServer() +"/divisions/" + divisionId + "/subdivisions",
                                                contentType: "application/json",
                                                type: "get",
                                                success: function (data) {
                                                    $.each(data, function (idx, item) {
                                                        htmlArea += "<option value='" + item.divisionName + "' exid='" + item.divisionId + "'>" + item.divisionName + "</option>";
                                                    });
                                                    $("#areaSelect").append(htmlArea);
                                                    $('#areaSelect').val(Area);
                                                }
                                            });
                                        }
                                        htmlCity += "<option value='" + item.divisionName + "' exid='" + item.divisionId + "'>" + item.divisionName + "</option>";
                                    });
                                    $("#citySelect").append(htmlCity);
                                    $('#citySelect').val(City);
                                }
                            });
                        }
                    }
                    html += "<option value='" + item.divisionName + "' exid='" + item.divisionId + "'>" + item.divisionName + "</option>";
                });
                $("#provinceSelect").append(html);
                $('#provinceSelect').val(Province);
            }
        });
        $("#provinceSelect").change(function () {
            var html = '<option value="" disabled selected style="display:none;">请选择</option>';
            $("#citySelect option").remove();
            $("#citySelect").append(html);
            $("#areaSelect option").remove();
            $("#areaSelect").append(html);
            var divisionId = $(this).find("option:selected").attr("exid");
            if ($(this).val() == "北京市" || $(this).val() == "天津市" || $(this).val() == "上海市" || $(this).val() == "重庆市") {
                $("#citySelect").append("<option value='" + $(this).val() + "' exid='" + divisionId + "'>" + $(this).val() + "</option>");
                return;
            }
            $.ajax({
                url: getServer() +"/divisions/" + divisionId + "/subdivisions",
                contentType: "application/json",
                type: "get",
                success: function (data) {
                    $.each(data, function (idx, item) {
                        html += "<option value='" + item.divisionName + "' exid='" + item.divisionId + "'>" + item.divisionName + "</option>";
                    });
                    $("#citySelect").append(html);
                }
            });
        });
        $("#citySelect").change(function () {
            if ($(this).val() == "") return;
            var html = '<option value="" disabled selected style="display:none;">请选择</option>';
            $("#areaSelect option").remove();
            $("#areaSelect").append(html);
            var divisionId = $(this).find("option:selected").attr("exid");
            $.ajax({
                url: getServer() +"/divisions/" + divisionId + "/subdivisions",
                contentType: "application/json",
                type: "get",
                success: function (data) {
                    $.each(data, function (idx, item) {
                        html += "<option value='" + item.divisionName + "' exid='" + item.divisionId + "'>" + item.divisionName + "</option>";
                    });
                    $("#areaSelect").append(html);
                }
            });
        });
    };

    // 编辑表单省市区
    var editProvince = function (Province, City, Area) {
        debugger;
        var html = "";
        $("#city").append(html);
        $("#area").append(html);
        $.ajax({
            url: getServer() +"/divisions/root/subdivisions",
            contentType: "application/json",
            type: "get",
            success: function (data) {
                $.each(data, function (idx, item) {
                    if (item.divisionName == Province) {
                        debugger;
                        var divisionId = item.divisionId;
                        var htmlCity = '';
                        if (Province == "北京市" || Province == "天津市" || Province == "上海市" || Province == "重庆市") {
                            $("#city").append("<option value='" + Province + "' exid='" + divisionId + "'>" + Province + "</option>");
                            $('#city').val(City);
                            var htmlArea = '';
                            $.ajax({
                                url: getServer() +"/divisions/" + divisionId + "/subdivisions",
                                contentType: "application/json",
                                type: "get",
                                success: function (data) {
                                    $.each(data, function (idx, item) {
                                        htmlArea += "<option value='" + item.divisionName + "' exid='" + item.divisionId + "'>" + item.divisionName + "</option>";
                                    });
                                    $("#area").append(htmlArea);
                                    $('#area').val(Area);
                                }
                            });

                        } else {
                            $.ajax({
                                url: getServer() +"/divisions/" + divisionId + "/subdivisions",
                                contentType: "application/json",
                                type: "get",
                                success: function (data) {
                                    debugger;
                                    $.each(data, function (idx, item) {
                                        if (item.divisionName == City) {
                                            var divisionId = item.divisionId;
                                            var htmlArea = '';
                                            $.ajax({
                                                url: getServer() +"/divisions/" + divisionId + "/subdivisions",
                                                contentType: "application/json",
                                                type: "get",
                                                success: function (data) {
                                                    $.each(data, function (idx, item) {
                                                        htmlArea += "<option value='" + item.divisionName + "' exid='" + item.divisionId + "'>" + item.divisionName + "</option>";
                                                    });
                                                    $("#area").append(htmlArea);
                                                    $('#area').val(Area);
                                                }
                                            });
                                        }
                                        htmlCity += "<option value='" + item.divisionName + "' exid='" + item.divisionId + "'>" + item.divisionName + "</option>";
                                    });
                                    $("#city").append(htmlCity);
                                    $('#city').val(City);
                                }
                            });
                        }
                    }
                    html += "<option value='" + item.divisionName + "' exid='" + item.divisionId + "'>" + item.divisionName + "</option>";
                });
                $("#province").append(html);
                $('#province').val(Province);
            }
        });
        $("#province").change(function () {
            var html = '<option value="" disabled selected style="display:none;">请选择</option>';
            $("#city option").remove();
            $("#city").append(html);
            $("#area option").remove();
            $("#area").append(html);
            var divisionId = $(this).find("option:selected").attr("exid");
            if ($(this).val() == "北京市" || $(this).val() == "天津市" || $(this).val() == "上海市" || $(this).val() == "重庆市") {
                $("#city").append("<option value='" + $(this).val() + "' exid='" + divisionId + "'>" + $(this).val() + "</option>");
                return;
            }
            $.ajax({
                url: getServer() +"/divisions/" + divisionId + "/subdivisions",
                contentType: "application/json",
                type: "get",
                success: function (data) {
                    $.each(data, function (idx, item) {
                        html += "<option value='" + item.divisionName + "' exid='" + item.divisionId + "'>" + item.divisionName + "</option>";
                    });
                    $("#city").append(html);
                }
            });
        });
        $("#city").change(function () {
            if ($(this).val() == "") return;
            var html = '<option value="" disabled selected style="display:none;">请选择</option>';
            $("#area option").remove();
            $("#area").append(html);
            var divisionId = $(this).find("option:selected").attr("exid");
            $.ajax({
                url: getServer() +"/divisions/" + divisionId + "/subdivisions",
                contentType: "application/json",
                type: "get",
                success: function (data) {
                    $.each(data, function (idx, item) {
                        html += "<option value='" + item.divisionName + "' exid='" + item.divisionId + "'>" + item.divisionName + "</option>";
                    });
                    $("#area").append(html);
                }
            });
        });
    }

    var initCasulatySelect = function () {
        $.ajax({
            url: getFxCasulatyEstimateController() + "/getValidDictItemsByDictCode/" + "人员伤亡",
            type: "get",
            success: function (data) {
                var mySelect = document.getElementById("casulatySelect");
                mySelect.add(new Option("请选择", ''), 0);
                for (var i = 0; i < data.length; i++) {
                    var name = data[i].dictItemName;
                    var code = data[i].dictItemCode;
                    mySelect.add(new Option(name, code));
                }
            }
        });
    };
    var initPeriodSelect = function () {
        $.ajax({
            url: getFxCasulatyEstimateController() + "/getValidDictItemsByDictCode/" + "时间段",
            type: "get",
            success: function (data) {
                var mySelect = document.getElementById("periodSelect");
                mySelect.add(new Option("请选择", ''), 0);
                for (var i = 0; i < data.length; i++) {
                    var name = data[i].dictItemName;
                    var code = data[i].dictItemCode;
                    mySelect.add(new Option(name, code));
                }
            }
        });
    };

    var initCasulatySelectFrom = function () {
        $.ajax({
            url: getFxCasulatyEstimateController() + "/getValidDictItemsByDictCode/" + "人员伤亡",
            type: "get",
            success: function (data) {
                var mySelect = document.getElementById("casulaty");
                mySelect.add(new Option("请选择", ''), 0);
                for (var i = 0; i < data.length; i++) {
                    var name = data[i].dictItemName;
                    var code = data[i].dictItemCode;
                    mySelect.add(new Option(name, code));
                }
            }
        });
    };
    var initPeriodSelectFrom = function () {
        $.ajax({
            url: getFxCasulatyEstimateController() + "/getValidDictItemsByDictCode/" + "时间段",
            type: "get",
            success: function (data) {
                var mySelect = document.getElementById("period");
                mySelect.add(new Option("请选择", ''), 0);
                for (var i = 0; i < data.length; i++) {
                    var name = data[i].dictItemName;
                    var code = data[i].dictItemCode;
                    mySelect.add(new Option(name, code));
                }
            }
        });
    };
    var initIntensitySelectFrom = function () {
        $.ajax({
            url: getFxCasulatyEstimateController() + "/getValidDictItemsByDictCode/" + "earthquakeIntensity",
            type: "get",
            success: function (data) {
                var mySelect = document.getElementById("intensity");
                mySelect.add(new Option("请选择", ''), 0);
                for (var i = 0; i < data.length; i++) {
                    var name = data[i].dictItemName;
                    var code = data[i].dictItemCode;
                    mySelect.add(new Option(name, code));
                }
            }
        });
    };
    var initDamageDegreeSelectFrom = function () {
        $.ajax({
            url: getFxCasulatyEstimateController() + "/getValidDictItemsByDictCode/" + "damageDegree",
            type: "get",
            success: function (data) {
                var mySelect = document.getElementById("damageDegree");
                mySelect.add(new Option("请选择", ''), 0);
                for (var i = 0; i < data.length; i++) {
                    var name = data[i].dictItemName;
                    var code = data[i].dictItemCode;
                    mySelect.add(new Option(name, code));
                }
            }
        });
    };

    var initSearchBlock = function () {
        SearchBlock.init("searchBlock");
    };
    var queryBtnBind = function () {
        $("#btnSearch").click(function () {
            if ($("#provinceSelect").val() == null) {
                Util.alert("请选择省");
                return;
            }
            if ($("#citySelect").val() == null) {
                Util.alert("请选择市");
                return;
            }
            if ($("#areaSelect").val() == null) {
                Util.alert("请选择区（县）");
                return;
            }
            createFxCasulatyEstimateGrid();
        });
        // 重置按钮
        $("#btnReset").click(function () {
            var html = '<option value="" disabled selected style="display:none;">请选择</option>';
            $("#citySelect option").remove();
			$("#citySelect").append(html);
			$("#areaSelect option").remove();
			$("#areaSelect").append(html);
            initProvinceSelect("北京市", "北京市", "东城区");
            $("#casulatySelect").val("");
            $("#periodSelect").val("");
        });
    };
    var createFxCasulatyEstimateGrid = function () {
        $("#fxCasulatyEstimateGrid").datagrid({
            url: getFxCasulatyEstimateController() + "/listFxCasulatyEstimates",
            method: "GET",
            fitColumns: true,
            autoRowHeight: false,
            columns: [[
//              {field: "ck", checkbox: true},
                {
                    field: 'province',
                    title: '省',
                    width: '14%',
                    align: 'center',
                },
                {
                    field: 'city',
                    title: '市',
                    width: '14%',
                    align: 'center',
                },
                {
                    field: 'area',
                    title: '区（县）',
                    width: '14%',
                    align: 'center',
                },
                {
                    field: 'intensity',
                    title: '烈度',
                    width: '10%',
                    align: 'center',
                    formatter: function (value) {
                        if (value == "6") {
                            return 'VI';
                        } else if (value == "7") {
                            return 'VII';
                        } else if (value == "8") {
                            return 'VIII';
                        } else if (value == "9") {
                            return 'IX';
                        } else if (value == "10") {
                            return 'X';
                        }
                    }
                },
                {
                    field: 'casulaty',
                    title: '人员伤亡',
                    width: '13%',
                    align: 'center',
                },
                {
                    field: 'period',
                    title: '时间段',
                    width: '13%',
                    align: 'center',
                },

                {
                    field: 'damageDegree',
                    title: '破坏程度',
                    width: '11%',
                    align: 'center',
                    formatter: function (value) {
                        if (value == "0") {
                            return '基本完好';
                        } else if (value == "1") {
                            return '轻微破坏';
                        } else if (value == "2") {
                            return '中等破坏';
                        } else if (value == "3") {
                            return '严重破坏';
                        } else if (value == "4") {
                            return '完全破坏';
                        }
                    }
                },
                {
                    field: 'calculatedValue',
                    title: '计算值（人）',
                    width: '11%',
                    align: 'center',
                    editor: {type: 'numberbox'},
                }
            ]],
            toolbar: [{
                iconCls: 'fa fa-download',
                text: "导出",
                handler: function () {
                    exportForm();
                }
            }],
            onClickCell: function (index, field, value) {
                if (endEditing()) {
                    $('#fxCasulatyEstimateGrid').datagrid('selectRow', index).datagrid('editCell', {
                        index: index,
                        field: field
                    });
                    editIndex = index;
                    mergeCells("fxCasulatyEstimateGrid", "province,city,area,intensity,casulaty,period,calculatedValue");
                }
            },
//          onDblClickCell: function (index, field, value) {
//				$("#fxCasulatyEstimateGrid").datagrid('endEdit', index);
//				debugger;
//				mergeCells("fxCasulatyEstimateGrid", "province,city,area,structureType");
//        	},
            onAfterEdit: function (index, row, changes) {
//             $("#fxCasulatyEstimateGrid").datagrid('endEdit', index);
//			    $.ajax({
//			        url : '要改变后台数据的controller路径?fieId1='+row.属性1,
//			        data:{fieId2:row.fieId}, //额外的参数
//			        dataType: "text",//响应结果为文本
//			        success:function (data) {
//			            $.messager.alert('消息', data);
//			        }
//			    });
                //console.log(index, row, changes);
                $.ajax({
                    url: getFxCasulatyEstimateController(),
                    contentType: "application/json",
                    data: JSON.stringify(row),
                    type: "put",
                    success: function (data) {
                        Util.alert(data.message);
                        createFxCasulatyEstimateGrid();
                    }
                });

            },
            queryParams: {
                province: $("#provinceSelect").val(),
                city: $("#citySelect").val(),
                area: $("#areaSelect").val(),
//              casulaty: $("#casulatySelect").val(),
//              period: $("#periodSelect").val(),
            },
            onLoadSuccess: function (data) {
                //垂直合并单元格
                mergeCells("fxCasulatyEstimateGrid", "province,city,area,intensity,casulaty,period,calculatedValue");
            },
//          pagination: true,
//          pageSize: 10
        });
    };
    $.extend($.fn.datagrid.methods, {
        editCell: function (jq, param) {
            return jq.each(function () {
                var opts = $(this).datagrid('options');
                var fields = $(this).datagrid('getColumnFields', true).concat(
                    $(this).datagrid('getColumnFields'));
                for (var i = 0; i < fields.length; i++) {
                    var col = $(this).datagrid('getColumnOption', fields[i]);
                    col.editor1 = col.editor;
                    if (fields[i] != param.field) {
                        col.editor = null;
                    }
                }
                $(this).datagrid('beginEdit', param.index);
                for (var i = 0; i < fields.length; i++) {
                    var col = $(this).datagrid('getColumnOption', fields[i]);
                    col.editor = col.editor1;
                }
            });
        }
    });
    var editIndex = undefined;

    //结束编辑
    function endEditing() {
        if (editIndex == undefined) {
            return true
        }
        if ($('#fxCasulatyEstimateGrid').datagrid('validateRow', editIndex)) {
            $('#fxCasulatyEstimateGrid').datagrid('endEdit', editIndex);
            editIndex = undefined;
            return true;
        } else {
            return false;
        }
    };

    //合并单元格方法
    /**
     * EasyUI DataGrid根据字段动态合并单元格
     * @param colList 要合并table的id, 此例子中是tTable
     * @param colList 要合并的列,多个列用逗号分隔(例如："tempParam,flowCode,queryParam");
     */
    function mergeCells(tableID, colList) {
        var colArray = colList.split(",");
        var tTable = $("#" + tableID);
        var tableRows = tTable.datagrid("getRows");
        var tableRowCnts = tableRows.length;
        var rowspan;
        var preTxt = "";
        var curTxt = "";
        for (j = colArray.length - 1; j >= 0; j--) {
            preTxt = "";
            rowspan = 1;
            for (i = 0; i <= tableRowCnts; i++) {
                if (i == tableRowCnts) {
                    curTxt = "";
                } else {
                    curTxt = tableRows[i][colArray[j]];
                }
                if (preTxt == curTxt) {
                    rowspan += 1;
                } else {
                    tTable.datagrid("mergeCells", {
                        index: i - rowspan,
                        field: colArray[j],//合并字段
                        rowspan: rowspan,
                        colspan: null
                    });
                    rowspan = 1;
                }
                preTxt = curTxt;
            }
        }
    };
    var getFxCasulatyEstimate = function (id) {
        $.ajax({
            url: getFxCasulatyEstimateController() + "/" + id,
            type: "get",
            success: function (data) {
                editProvince(data.province, data.city, data.area);
                Tool.deserialize("fxCasulatyEstimateForm", data);
            }
        });
    };

    var addFxCasulatyEstimate = function () {
        var slidebar = Util.slidebar({
            url: fxCasulatyEstimateFormHtml,
            width: "580px",
            cache: false,
            close: true,
            afterLoad: function () {
                initcreateProvinceForm
                initCasulatySelectFrom();
                initPeriodSelectFrom();
                initIntensitySelectFrom();
                initDamageDegreeSelectFrom();
                formValidator();
                $("#saveBtn").on("click", function () {
                    if ($("#fxCasulatyEstimateForm").valid()) {
                        var data = Tool.serialize("fxCasulatyEstimateForm");
                        $.ajax({
                            url: getFxCasulatyEstimateController(),
                            contentType: "application/json",
                            data: JSON.stringify(data),
                            type: "post",
                            success: function (data) {
                                Util.alert(data.message);
                                slidebar.close();
                                createFxCasulatyEstimateGrid();
                            }
                        });
                    }
                });
            }
        });
    };
    /**
     * 计算
     */
    var calculate = function () {
        debugger
        var loading = Loading({
            text: "正在加载"
        });
        loading.show();
        $.ajax({
            url: getFxCasulatyEstimateController() + "/calculate",
            type: "get",
            data: {
                province: $("#provinceSelect").val(),
                city: $("#citySelect").val(),
                area: $("#areaSelect").val(),
                casulaty: $("#casulatySelect").val(),
                period: $("#periodSelect").val(),
            },
            success: function (data) {
                console.log(data)
                loading.close();
                Util.alert(data);
                // 列表
                createFxCasulatyEstimateGrid();
            }
        });
    }
    /**
     * 导出
     */
    var exportForm = function () {
        let province = $("#provinceSelect").val();
        let city = $("#citySelect").val();
        let area = $("#areaSelect").val();
        let casulaty = $("#casulatySelect").val();
        let period = $("#periodSelect").val();
        window.location.href = getFxCasulatyEstimateController() + "/export?province=" + province + "&city=" + city
            + "&area=" + area + "&casulaty=" + casulaty + "&period=" + period;
    };
    window._editFxCasulatyEstimate = function (fxCasulatyEstimateId) {
        var slidebar = Util.slidebar({
            url: fxCasulatyEstimateFormHtml,
            width: "580px",
            cache: false,
            close: true,
            afterLoad: function () {
                initCasulatySelectFrom();
                initPeriodSelectFrom();
                initIntensitySelectFrom();
                initDamageDegreeSelectFrom();
                formValidator();
                getFxCasulatyEstimate(fxCasulatyEstimateId);
                $("#saveBtn").on("click", function () {
                    if ($("#fxCasulatyEstimateForm").valid()) {
                        var data = Tool.serialize("fxCasulatyEstimateForm");
                        $.ajax({
                            url: getFxCasulatyEstimateController(),
                            contentType: "application/json",
                            data: JSON.stringify(data),
                            type: "put",
                            success: function (data) {
                                Util.alert(data.message);
                                slidebar.close();
                                createFxCasulatyEstimateGrid();
                            }
                        });
                    }
                });
            }
        });
    };
    var deleteFxCasulatyEstimate = function () {
        var rows = $("#fxCasulatyEstimateGrid").datagrid("getSelections");
        if (rows == null || rows.length == 0) {
            Util.alert("请选择一行数据!");
            return;
        }
        Util.confirm("是否要删除选中的数据?", function () {
            var ids = "";
            $.each(rows, function (i, row) {
                ids += row.id + ",";

            });
            ids = ids.substr(0, ids.length - 1);
            $.ajax({
                url: getFxCasulatyEstimateController(),
                data: {
                    ids: ids
                },
                type: "delete",
                success: function (data) {
                    createFxCasulatyEstimateGrid();
                }
            });
        }, function () {
            return;
        });

    };

    return {
        init: init
    };
});
